package util;

import bean.User;
import common.AppVariable;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 登陆权限的确认；
 * 注意要实现3个方法，如果不加会报错
 */
@WebFilter("/*")
public class LoginAuthorServlet implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("DemoFilter init");
    }
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        String requestURI = req.getRequestURI();

        // 1.不登录也可以访问的连接，就放行
        // TODO:如果把contains换成equals
        if (requestURI.contains("/login")
                || requestURI.contains("/register")
                //需要放行这些静态文件
                || requestURI.contains("/js/")
                || requestURI.contains("/css/")
                || requestURI.contains("/common.js")
                || requestURI.contains("/login.html")
                || requestURI.contains("/regist.html")
        ){
            // 对于登陆，注册，验证码请求的连接，就放行
            filterChain.doFilter(servletRequest, servletResponse);
        }else{
            // 2.其他连接必须登陆才能访问
            HttpSession session = req.getSession();
            User user = (User) session.getAttribute(AppVariable.SESSION_USERINFO_KEY);
            // 如果没有登陆，就去登陆页面
            if (user==null){
                resp.sendRedirect(req.getContextPath()+"/login.html");
            }else {
                //登陆了,就放行
                filterChain.doFilter(servletRequest, servletResponse);
            }
        }
    }

    @Override
    public void destroy() {
        System.out.println("DemoFilter destroy");
    }
}

